package cn.jtfadmin.base.doc.swagger;

import com.thoughtworks.qdox.JavaProjectBuilder;
import com.thoughtworks.qdox.model.DocletTag;
import com.thoughtworks.qdox.model.JavaClass;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import springfox.documentation.service.ResourceGroup;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.ApiListingBuilderPlugin;
import springfox.documentation.spi.service.contexts.ApiListingContext;


import java.util.Optional;

import static springfox.documentation.spring.web.paths.Paths.removeAdjacentForwardSlashes;
import static springfox.documentation.spring.web.paths.Paths.splitCamelCase;
import static springfox.documentation.swagger.common.SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER;

/**
 * @author
 */
@Component
@Order(SWAGGER_PLUGIN_ORDER)
public class DocApiListingReader implements ApiListingBuilderPlugin {
    private final JavaProjectBuilder javaProjectBuilder;

    @Autowired
    public DocApiListingReader(
            JavaProjectBuilder javaProjectBuilder) {
        this.javaProjectBuilder = javaProjectBuilder;

    }



    @Override
    public void apply(ApiListingContext apiListingContext) {
        ResourceGroup group = apiListingContext.getResourceGroup();
        JavaClass javaClass = null;
        Optional<? extends Class<?>> controllerClass = group.getControllerClass();
        if(!controllerClass.isPresent()){
            apiListingContext.apiListingBuilder()
                    .description(group.getGroupName());
            return;

        }
        Class<?> clazz = controllerClass.get();
        javaClass = javaProjectBuilder.getClassByName(clazz.getName());
        String description = "";
        String version = null;
        if(javaClass == null){
            description = splitCamelCase(controllerClass.get().getSimpleName(), "");
        }else {
            description = ObjectUtils.defaultIfNull(javaClass.getComment(), "");
            DocletTag authorTag  = javaClass.getTagByName("author");
            if(authorTag != null ){
                description = description +" 作者:"+authorTag.getValue();
            }
            DocletTag versionTag  = javaClass.getTagByName("version");
            if(versionTag != null ){
                version = versionTag.getValue();
            }
        }
        apiListingContext.apiListingBuilder()
                .description(description).apiVersion(version);
    }

    @Override
    public boolean supports(DocumentationType delimiter) {
        return true;
    }
}
